<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>用户列表</title>
    <link rel="stylesheet" href="./layui/css/layui.css">
</head>
<body style="padding: 20px 10px;">

<!-- 你的 HTML 代码 -->
<span class="layui-breadcrumb">
  <a href="/index.html">首页</a>
  <a><cite>用户列表</cite></a>
</span>
<div class="demoTable" style="margin-top: 10px;">
    用户：
    <div class="layui-inline">
        <input class="layui-input" placeholder="搜索用户名称" name="name" id="demoReload" autocomplete="off">
    </div>
    <button class="layui-btn" id="demoReloadBtn">搜索</button>
</div>
<table id="demo" lay-filter="test"></table>
<script type="text/html" id="barDemo">
    <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-xs" lay-event="lock">锁定</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="permission">权限</a>
    <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="del">删除</a>
</script>
<script type="text/html" id="toolbarDemo">
    <div class="layui-btn-container">
        <button class="layui-btn layui-btn-sm" lay-event="add">添加用户</button>
    </div>
</script>
<form class="layui-form" lay-filter="formTest" action="" id="addUser" style="display:none;width: 500px;padding: 20px;">
    <input type="hidden" name="id">
    <input type="hidden" name="status">
    <div class="layui-form-item">
        <label class="layui-form-label">用户名称</label>
        <div class="layui-input-block">
            <input type="text" name="name" required  lay-verify="required" placeholder="请输入用户名称" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">请求Key</label>
        <div class="layui-input-inline" style="width: 260px;">
            <input type="text" id="requestKey" name="requestKey" required  lay-verify="required" placeholder="请输入请求Key" autocomplete="off" class="layui-input">
        </div>
        <button type="button" class="layui-btn" id="randomKeyBtn">生成随机key</button>
    </div>
    <div class="layui-form-item layui-form-text">
        <label class="layui-form-label">白名单</label>
        <div class="layui-input-block">
            <textarea name="whiteList" placeholder="多个ip地址使用逗号分割" class="layui-textarea"></textarea>
        </div>
    </div>
    <div class="layui-form-item">
        <div class="layui-input-block">
            <button class="layui-btn" lay-submit lay-filter="formDemo">确定</button>
            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
        </div>
    </div>
</form>
<script src="./layui/layui.js"></script>
<script>
layui.use(['element', 'layer', 'form', 'table', 'jquery'], function(){
  var layer = layui.layer;
  var table = layui.table;
  var form = layui.form;
  var $ = layui.$;

   form.on('submit(formDemo)', function(data){
    $.ajax({
        type: "POST",
        url: "/user/save",
        data: JSON.stringify(data.field),
        contentType: 'application/json',
        dataType: "json",
        success: function (result) {
            if (result.code == 0) {
                window.location.reload();
            } else {
                layer.msg(result.msg, {icon: 5});
            }
        }
    });
    return false;
  });

   //第一个实例
  var tableData = [];
  table.render({
    elem: '#demo'
    ,toolbar: '#toolbarDemo'

    ,url: '/user/findPage' //数据用户
    ,method: 'post'
    ,request: {
        pageName: 'pageNum' //页码的参数名称，默认：page
        ,limitName: 'pageSize' //每页数据量的参数名，默认：limit
    }
    ,page: true //开启分页
    ,headers: {}
    ,done: function(res, curr, count){
        tableData = res.data;
    }
    ,parseData: function(res){ //res 即为原始返回的数据
        return {
          "code": res.code, //解析用户状态
          "msg": res.msg, //解析提示文本
          "count": res.data.total, //解析数据长度
          "data": res.data.list //解析数据列表
        };
    }
    ,response: {
        statusName: 'code' //规定数据状态的字段名称，默认：code
        ,statusCode: '0000' //规定成功的状态码，默认：0
        ,msgName: 'msg' //规定状态信息的字段名称，默认：msg
        ,countName: 'count' //规定数据总数的字段名称，默认：count
        ,dataName: 'data' //规定数据列表的字段名称，默认：data
    }
    ,contentType: 'application/json'
    ,cols: [[ //表头
      {field: 'id', title: '序号', type: 'numbers', width:80, fixed: 'left'}
      ,{field: 'name', title: '用户名称', edit: 'text'}
      ,{field: 'requestKey', title: '请求Key'}
      ,{field: 'whiteList', title: '白名单', edit: 'text'}
      ,{field: 'status', title: '状态', width: 80, templet: function(d){return d.status == 1 ? "正常" : "锁定";}}
      ,{fixed: 'right', title: '操作', width: 220, align:'center', toolbar: '#barDemo'}
    ]]
  });

  //触发事件
    table.on('toolbar(test)', function(obj){
      switch(obj.event){
        case 'add':
            layer.open({
              type: 1,
              title: '添加用户',
              area: '600px',
              content: $('#addUser') //这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
            });
        break;
      };
    });

    //工具条事件
    table.on('tool(test)', function(obj){ //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
      var data = obj.data; //获得当前行数据
      var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）

      if(layEvent === 'edit'){ //编辑
        layer.open({
          type: 1,
          title: '修改用户',
          area: '600px',
          content: $('#addUser') //这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
        });
        //给表单赋值
        form.val("formTest", { //formTest 即 class="layui-form" 所在元素属性 lay-filter="" 对应的值
          "id": data.id
          ,"name": data.name
          ,"requestKey": data.requestKey
          ,"whiteList": data.whiteList
          ,"status": data.status
        });
      } else if(layEvent === 'del'){ //删除
        if(!data.id){
            obj.del();
            return false;
        }
        layer.confirm('确认删除用户吗', function(index){
          layer.close(index);
          //向服务端发送删除指令
          $.ajax({
            type: "POST",
            url: "/user/deleteById",
            data: JSON.stringify({"id":data.id}),
            contentType: 'application/json',
            dataType: "json",
            success: function (result) {
                if (result.code == 0) {
                    layer.msg('删除成功', {icon: 6})
                    obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
                } else {
                    layer.msg(result.msg, {icon: 5});
                }
            }
          });
        });
      } else if(layEvent === 'lock'){ // 锁定
        if(!data.id){
            return false;
        }
        $.ajax({
            type: "POST",
            url: "/user/lock",
            data: JSON.stringify({"id":data.id}),
            contentType: 'application/json',
            dataType: "json",
            success: function (result) {
                if (result.code == 0) {
                    window.location.reload();
                } else {
                    layer.msg(result.msg, {icon: 5});
                }
            }
          });
      } else if(layEvent === 'permission'){ // 权限
        layer.open({
          type: 2,
          content: 'user_interface.html?userId=' + data.id,
          area: ['800px', '500px']
        });
      } else if(layEvent === 'LAYTABLE_TIPS'){
        layer.alert('Hi，头部工具栏扩展的右侧图标。');
      }
    });

    table.on('edit(test)', function(obj){ //注：edit是固定事件名，test是table原始容器的属性 lay-filter="对应的值"
      $.ajax({
        type: "POST",
        url: "/user/save",
        data: JSON.stringify(obj.data),
        contentType: 'application/json',
        dataType: "json",
        success: function (result) {
            if (result.code == 0) {
                layer.msg('保存成功', {icon: 6})
            } else {
                layer.msg(result.msg, {icon: 5});
            }
        }
      });
    });

    $("#demoReloadBtn").click(function(){
        var name = $("#demoReload").val();
        table.reload('demo', {where: {queryModel: {name: name}}}, true);
    });

    $("#randomKeyBtn").click(function(){
        $("#requestKey").val(randomString());
    });

    window.randomString = function(e){
      e = e || 32;
      var t = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678",
      a = t.length,
      n = "";
      for (i = 0; i < e; i++) n += t.charAt(Math.floor(Math.random() * a));
      return n;
    };
});
</script>
</body>
</html>